<?php

declare(strict_types=1);
/**
 * 文章标签关联关系数据访问类
 * 作者 薛原
 * 日期 2025-10-17
 */
namespace App\Repository;
use App\Model\ArticleTag;
use Hyperf\Di\Annotation\Inject;

class ArticleTagRepository
{
    #[Inject]
    private ArticleTag $articleTagModel;

    #[Inject]
    private TagRepository $tagRepository;

    /**
     * 合并标签属性
     * @param $data
     * @param string $key
     * @return mixed
     */
    public function mergeArticleTagData($data, $key = "id")
    {
        $ids = [];
        foreach($data as $info){
            $ids[] = $info[$key];
        }
        $ids = array_unique($ids);
        if(count($ids) == 0){
            return $data;
        }
        $article_tag_list = $this->articleTagModel->whereIn("article_id",$ids)->select(["tag_id","article_id"])->get()->toArray();
        $tag_ids = [];
        foreach($article_tag_list as $info){
            $tag_ids[] = $info['tag_id'];
        }
        $tag_ids = array_unique($tag_ids);
        $tag_dic = $this->tagRepository->getDicByIds($tag_ids);
        foreach($article_tag_list as $k => $v){
            if(isset($tag_dic[$info['tag_id']])){
                $article_tag_list[$k]['name'] = $tag_dic[$v['tag_id']]['name'];
                $article_tag_list[$k]['id'] = $tag_dic[$v['tag_id']]['id'];
            }else{
                $article_tag_list[$k]['name'] = "";
                $article_tag_list[$k]['id'] = "";
            }
        }
        $tag_group = \App\Lib\DataFormart::dataToGroup($article_tag_list,"article_id");
        foreach($data as $k => $v){
            if(isset($tag_group[$v[$key]])){
                $data[$k]['tags'] = $tag_group[$v[$key]];
            }else{
                $data[$k]['tags'] = [];
            }
        }
        return $data;
    }

    /**
     * 获取文章的标签关联id
     * @param $article_id
     * @return \Hyperf\Utils\Collection
     */
    public function getTagsIdsByArticleId($article_id)
    {
        $ids = $this->articleTagModel->where("article_id", $article_id)->pluck("tag_id");
        return $ids;
    }
    /**
     * 增加文件标签引用关系
     * @param $article_id
     * @param $tags_list
     */
    public function addRelation($article_id,$tags_list)
    {
        foreach($tags_list as $info){
            $obj = ["article_id"=>$article_id,"tag_id"=>$info['id']];
            $this->articleTagModel->insert($obj);
        }
    }

    /**
     * 删除文章标签引用关系
     * @param $article_id
     * @param $tags_ids
     */
    public function removeRelation($article_id, $tags_ids)
    {
        $this->articleTagModel->where("article_id", $article_id)->whereIn("tag_id",$tags_ids)->delete();
    }

}